package com.cp.order.platform.web;

import java.util.HashMap;
import java.util.Map;

import com.cp.order.model.SysUser;
import com.cp.order.platform.BaseController;
import com.cp.order.utils.IWebUtils;
import com.cp.order.utils.ParseMD5;
import com.jfinal.kit.StrKit;

public class UserController extends BaseController {

	public void index() {
		renderFreeMarker("user.html");
	}

	public void addUser() {
		renderFreeMarker("userAdd.html");
	}

	public void editUser() {
		renderFreeMarker("userEdit.html");
	}

	public void modifyPwd() {
		renderFreeMarker("modifyPwd.html");
	}

	public void list() {
		int cpage = getParaToInt("cpage", 1);
		int pageSize = getParaToInt("pagesize", 10);
		HashMap<String, String> params = new HashMap<>();
		returnOK(SysUser.dao.queryList(params, cpage, pageSize));
	}

	public void add() {
		SysUser user = getModel(SysUser.class, "user");
		user.setPwd(ParseMD5.parseStrToMd5U32("123456"));
		user.setStatus(0);
		if (user.save()) {
			returnOK();
		} else {
			returnBusinessError("添加失败");
		}
	}

	public void update() {
		SysUser user = getModel(SysUser.class, "user");
		if (user.update()) {
			returnOK();
		} else {
			returnBusinessError("修改失败");
		}
	}

	public void doModifyPwd() {
		String oldPwd = getPara("oldPwd");
		String newPwd = getPara("newPwd");

		if (!StrKit.isBlank(oldPwd) && !StrKit.isBlank(newPwd)) {
			SysUser user = IWebUtils.getCurrentSysUser(this);
			if (user.getPwd().equals(ParseMD5.parseStrToMd5U32(oldPwd))) {
				user.setPwd(ParseMD5.parseStrToMd5U32(newPwd));
				if (user.update()) {
					// 更新session
					setSessionAttr("userSession", user);
					returnOK();
				} else {
					returnBusinessError("修改失败");
				}
			} else {
				returnBusinessError("原密码不正确");
			}
		} else {
			returnBusinessError("密码不能为空");
		}
	}

	public void delete() {
		int id = getParaToInt("id");
		SysUser user = new SysUser();
		user.setId(id);
		user.setStatus(1);// 逻辑删除
		if (user.update()) {
			returnOK();
		} else {
			returnBusinessError("删除失败");
		}
	}

	public void judge() {
		SysUser user = SysUser.dao.getUserByCode(getPara("userCode"));
		Map<String, Object> map = new HashMap<String, Object>();
		if (user == null) {
			map.put("isHas", false);
		} else {
			map.put("isHas", true);
		}
		returnOK(map);
	}

}
